package main

import (
	pb "ihos/ihos"
	"log"

	tm "github.com/golang/protobuf/ptypes/timestamp"
	"github.com/lib/pq"
)

type guahao_shuju struct {
	id          int32
	guahao      int32
	create_time int64
	doctor_id   int32
	patient_id  int32
	sfz         string
	bingli_rtf  string
	icd_list    pq.Int64Array
	bingli_all  string
	bingli_bmp  []byte
}

func (d *guahao_shuju) GetFromDB(id int32) error {
	sql := "SELECT id,guahao,create_time,doctor_id,patient_id,sfz,bingli_rtf,icd_list,bingli_all,bingli_bmp FROM guahao_shuju WHERE id=$1"
	log.Println(sql)
	return DBConn.db.QueryRow(sql, id).Scan(&d.id, &d.guahao, &d.create_time, &d.doctor_id, &d.patient_id, &d.sfz, &d.bingli_rtf, &d.icd_list, &d.bingli_all, &d.bingli_bmp)
}

func (d *guahao_shuju) GetFromDBByGuaHao() error {
	sql := "SELECT id,guahao,create_time,doctor_id,patient_id,sfz,bingli_rtf,icd_list,bingli_all,bingli_bmp FROM guahao_shuju WHERE guahao=$1 ORDER BY id DESC LIMIT 1"
	return DBConn.db.QueryRow(sql, d.guahao).Scan(&d.id, &d.guahao, &d.create_time, &d.doctor_id, &d.patient_id, &d.sfz, &d.bingli_rtf, &d.icd_list, &d.bingli_all, &d.bingli_bmp)
}

func (d *guahao_shuju) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE guahao_shuju set guahao=$1,create_time=$2,doctor_id=$3,patient_id=$4,sfz=$5,bingli_rtf=$6,icd_list=$7,bingli_all=$8,bingli_bmp=$9 where id=$10 RETURNING id"
		err = DBConn.db.QueryRow(sql, d.guahao, d.create_time, d.doctor_id, d.patient_id, d.sfz, d.bingli_rtf, d.icd_list, d.bingli_all, d.bingli_bmp, d.id).Scan(&d.id)
	} else { //insert
		sql = "INSERT INTO guahao_shuju(guahao,create_time,doctor_id,patient_id,sfz,bingli_rtf,icd_list,bingli_all,bingli_bmp)VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING id"
		err = DBConn.db.QueryRow(sql, d.guahao, d.create_time, d.doctor_id, d.patient_id, d.sfz, d.bingli_rtf, d.icd_list, d.bingli_all, d.bingli_bmp).Scan(&d.id)
	}
	return err
}

func (d *guahao_shuju) toPB() *pb.GuaHaoShuJu {
	gs := &pb.GuaHaoShuJu{
		ID:          d.id,
		GUHAO_ID:    d.guahao,
		CREATE_TIME: &tm.Timestamp{Seconds: d.create_time},
		YISHENG_ID:  d.doctor_id,
		HUANZHE_ID:  d.patient_id,
		SFZ:         d.sfz,
		BINGLI_RTF:  d.bingli_rtf,
		ICDS:        make([]*pb.ICD, 0),
		BINGLI_ALL:  d.bingli_all,
		BINGLI_BMP:  d.bingli_bmp,
	}
	for _, v := range d.icd_list {
		icd := &icd{id: int32(v)}
		if err := icd.GetFromDB(icd.id); err != nil {
			log.Println(err)
		} else {
			gs.ICDS = append(gs.ICDS, icd.toPB())
		}
	}
	return gs
}

func (d *guahao_shuju) fromPB(in *pb.GuaHaoShuJu) *guahao_shuju {
	d.id = in.GetID()
	d.guahao = in.GetGUHAO_ID()
	d.create_time = in.GetCREATE_TIME().GetSeconds()
	d.doctor_id = in.GetYISHENG_ID()
	d.patient_id = in.GetHUANZHE_ID()
	d.sfz = in.GetSFZ()
	d.bingli_rtf = in.GetBINGLI_RTF()
	d.icd_list = make([]int64, 0)
	for _, v := range in.GetICDS() {
		d.icd_list = append(d.icd_list, int64(v.GetID()))
	}
	d.bingli_all = in.GetBINGLI_ALL()
	d.bingli_bmp = in.GetBINGLI_BMP()
	return d
}
